<template>
  <div id="roleName">
    <div class="management">
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>

        <el-breadcrumb-item>基础数据</el-breadcrumb-item>

        <el-breadcrumb-item>角色名称</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 用户角色 -->
      <!-- elment卡片组件 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <!-- 文字按钮 -->
          <el-button
            type="text"
            class="el-icon-circle-plus-outline"
            @click="dialogFormVisible = true"
          >新增角色</el-button>

          <el-checkbox v-model="checKed" class="checked">允许拖拽</el-checkbox>

          <!-- 新增角色弹出组件 -->
          <el-dialog
            title="新增角色信息"
            :visible.sync="dialogFormVisible"
            center
            :modal-append-to-body="false"
          >
            <el-form status-icon label-width="100px" class="demo-ruleForm">
              <el-form-item label="角色名称" prop="valuEp">
                <el-input type="text" v-model="valuEp" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="newRole(valuEp)">添加</el-button>
                <el-button @click="dialogFormVisible=false">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </div>
        <!-- 表格 -->
        <table class="dataTabble" border="0" cellspacing="0">
          <thead>
            <tr class="table-tr">
              <th width="20">#</th>
              <th width="200">角色名称</th>
              <th width="180">操作</th>
            </tr>
          </thead>
          <!-- draggable拖来拽排序组件 -->
          <!-- elment设为标签tbody属性 默认下是div。option配置animation动画时间，sort：是
          否可拖拽。@end拖拽后执行的函数-->
          <draggable
            v-model="tableList"
            element="tbody"
            :options="{animation:1000,sort:checKed}"
            @end="sortsuCcess()"
          >
            <tr class="table-tr" v-for="(item,index) in tableList" :key="index">
              <td>{{index+1}}</td>
              <td>{{item.userTypeTypeName}}</td>
              <td>
                <div class="tabopa">
                  <el-button size="small" @click="edIt(item)">编辑</el-button>
                  <el-button
                    v-has
                    type="danger"
                    :disabled="item.disable"
                    size="small"
                    @click="deLet(index)"
                  >删除</el-button>
                </div>
              </td>
            </tr>
          </draggable>
        </table>
      </el-card>

      <!-- 编辑角色 -->
      <el-dialog
        title="修改角色信息"
        :visible.sync="centerDialogVisible"
        center
        :modal-append-to-body="false"
      >
        <el-form status-icon label-width="100px" class="demo-ruleForm">
          <el-form-item label="角色名称" prop="tableData">
            <el-input type="text" v-model="tableData.userTypeTypeName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="modiFy(tableData.userTypeTypeName)">提交</el-button>
            <el-button @click="centerDialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 引入插件
import draggable from "vuedraggable";
export default {
  //components 托拉拽排序插件注册
  components: {
    draggable
  },
  // data数据属性
  data() {
    return {
      // 新增角色名称
      valuEp: "",
      // 修改角色组件属性
      centerDialogVisible: false,
      // 新增角色组件属性
      dialogFormVisible: false,
      // 多选框属性
      checKed: true,
      // 角色数据
      tableList: [],
      // 当前的角色数据
      tableData: "",
      indexs:0,
    };
  },
  //在渲染html前调用，初始化属性在渲染视图！
  created() {
    this.rendeRing();
  },
  // 事件方法执行
  methods: {
    // 角色数据
    rendeRing() {
      let _this = this;
      _this.$get("/api/UserType/GetUserRoles").then(res => {
        _this.tableList = res.data;
      });
    },
    // 拖拽排序函数
    sortsuCcess() {
      let _this = this;
      // forEach循环data：tableList角色数据属性，item.userTypeSortNo主键赋值！
      _this.tableList.forEach((item, index) => {
        item.userTypeSortNo = index + 1;
      });
      _this
        .$post("/api/UserType/OrderUserRoleNo", _this.tableList)
        .then(res => {
          if (_this.checKed == false) {
            return;
          } else if (res.data.code == 0) {
            //状态code为零则没变化
            _this.$message("没有变化！");
          } else {
            _this.$message({
              message: "排序成功",
              type: "success"
            });
          }
          _this.rendeRing();
        });
    },

    // 新增角色
    newRole() {
      let _this = this;
      let index = _this.tableList.findIndex(
        //findIndex默认遍历 tableList数组 将数组中的每个对象传入item
        (item, index) => {
          item.userTypeTypeName == _this.valuEp; //item.userTypeTypeName等于_this.valuEp（新增角色input里值）
          item.userTypeSortNo = index + 1;
        }
      );
      console.log(_this.tableList);
      if (index == -1) {
        //当item.userTypeTypeName里不存在_this.valuEp（新增角色input里的值）执行下面的axios请求
        _this
          .$post("/api/UserType/AddUserRole?userRoleName=" + _this.valuEp) //新增角色接口地址
          .then(res => {
            if (res.data.code == -2) {
              _this.$message.error("参数错误");
            } else {
              _this.$message({
                message: "添加成功！",
                type: "success"
              });
              _this.valuEp = "";
            }
            _this.tableList.push({
              disable: res.data.data.disable,
              userTypeId: res.data.data.userTypeId,
              userTypeTypeName: res.data.data.userTypeTypeName
            });
          });
      } else {
        this.$message.error("角色名称已存在!！");
      }
    },
    // 删除角色
    deLet(e) {
      let _this = this;
      console.log(e);
      _this
        .$confirm("确定删除？, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          _this
            .$post(
              //删除角色接口地址
              "/api/UserType/RemoveUserRole?userRoleId=" +
                _this.tableList[e].userTypeId
            )
            .then(function(res) {
              console.log(res);
              _this.$message({
                message: "删除成功！",
                type: "success"
              });
              _this.tableList.splice(e, 1);
            });
        })
        .catch(() => {
          _this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 编辑角色
    edIt(item) {
      this.indexs=this.tableList.indexOf(item)
      this.centerDialogVisible = !this.centerDialogVisible;
      this.tableData = JSON.parse(JSON.stringify(item));
    },
    // 修改角色
    modiFy(e) {
      console.log(e);
      let _this = this;
      if (_this.tableData.userTypeTypeName != "") {
        //修改角色接口地址
        _this
          .$post(
            "/api/UserType/ModifyUserRole?id=" +
              _this.tableData.userTypeId +
              "&&userRoleName=" +
              e +
              ""
          )
          .then(res=>{
            console.log(res);
            if (res.data.code == -2) {
              _this.$message.error("角色名称已存在！");
            } else if (res.data.code == 0) {
              _this.$message("数据没有变化！");
              _this.centerDialogVisible = true;
            } else {
              _this.$message({
                message: "修改成功",
                type: "success"
              });
              _this.tableList[_this.indexs].userTypeTypeName=e
              _this.centerDialogVisible = false;
            }
          })
          .catch(error => {
            console.log(error);
          });
      } else {
        alert("不能为空！");
      }
    }
  }
};
</script>

<style lang="less" scoped>
.management {
  width: 100%;
  margin: auto;
}
.dataTabble {
  width: 99%;
  text-align: center;
  margin: auto;
  // /deep/深度选择
  /deep/.table-tr {
    th {
      height: 50px;
      border-bottom: 1px solid #dddddd;
    }
    td {
      height: 50px;
      border-bottom: 1px solid #dddddd;
    }
  }
}

.demo-ruleForm {
  text-align: center;
}
.checked {
  margin-left: 20px;
}
.breadcrumb {
  margin-bottom: 20px;
}
</style>
